package org.letva.toink.util;

import org.apache.log4j.Logger;
import org.hibernate.Interceptor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

    private static final Logger log = Logger.getLogger(HibernateUtil.class);
    private static final SessionFactory sessionFactory;
    private static Session session;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().
                    configure().
                    buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
        	ex.printStackTrace();
            log.fatal("Initial SessionFactory creation failed. Cause: " + ex.getCause());
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Session getSession(Interceptor interceptor) {
        if (session != null) {
            return session;
        }
        session = openSession(interceptor);
        return session;
    }

    public static Session getSession() {
        if (session != null) {
            return session;
        }
        session = openSession(null);
        return session;
    }
    
    public static Session openSession(Interceptor interceptor) {
        Session session;
        if (interceptor == null) {
            session = sessionFactory.openSession();
        } else {
            session = sessionFactory.openSession(interceptor);
        }
        log.debug("Session created, interceptor: " + interceptor);
        return session;
    }
}
